package org.lzy.shop.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 * 使用ViewBinding的MVVM基础Fragment
 * @param VB 视图绑定类型
 * @param VM ViewModel类型
 * @param inflate 视图绑定的膨胀函数
 */
abstract class BaseMvvmFragment<VB : ViewBinding, VM : ViewModel>(
    private val inflate: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : BaseFragment<VB>(inflate) {

    // ViewModel
    protected lateinit var mViewModel: VM


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initViewModel()
        super.onViewCreated(view, savedInstanceState)
    }

    fun initViewModel() {
        try {
            val argument = (this.javaClass.genericSuperclass as? ParameterizedType)?.actualTypeArguments
            if (argument != null && argument.size > 1 && argument[1] is Class<*>) {
                mViewModel = ViewModelProvider(this).get(argument[1] as Class<VM>)
            } else {
                throw IllegalArgumentException("ViewModel类型参数无效，请检查泛型声明")
            }
        } catch (e: Exception) {
            throw RuntimeException("初始化ViewModel失败", e)
        }
    }


}